<?php
declare (strict_types=1);

namespace app\exam\model;

use app\common\model\{BaseModel, ProductType};
use think\model\concern\SoftDelete;

/**
 * 试卷模型
 */
class Paper extends BaseModel
{
    use softDelete;
    /**
     * 表名
     * @var string
     */
    protected $name = 'exam_paper';

    /**
     * 定义字段类型
     * @var [type]
     */
    protected $type = [
        'module_id'     => 'intger',
    ];

    /**
     * 定义字段类型
     * @var [type]
     */
    protected $hidden = [
        'create_time', 'update_time', 'delete_time',
    ];

    /**
     * 开考状态
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-04-29
     * @param  string $value [description]
     * @param  [type] $data  [description]
     * @return [type]        [description]
     */
    public function getExamStatusAttr($value='', $data)
    {
        if ( $data['start_time'] && $data['end_time'] ) {
            return ($data['start_time'] < time() && $data['end_time'] > time()) ? 1 : 0;
        } else if ( !$data['start_time'] && !$data['end_time'] ) {
            return 1;
        } else {
            return $data['start_time'] ? ($data['start_time'] < time() ? 1 : 0) : ($data['end_time'] > time() ? 1 : 0);
        }
    }

    /**
     * 关联部分
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date     21/03/29
     * @return \think\model\relation\HasMany
     */
    public function parts()
    {
        return $this->hasMany(PaperParts::class, 'paper_id');
    }

    /**
     * 购买人数
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-03-31
     * @return [type] [description]
     */
    public function boughtNum()
    {
        return $this
        ->hasMany(OrderItem::class, 'product_id')
        ->whereProductTypeId(ProductType::getProductIdByKey('exam'))
        ->join('payment_order po', "po.order_no=".env('database.prefix', '')."payment_order_item.order_no")
        ->where('status', 'IN', '20,30,40');
    }

    /**
     * 试卷关联公开考试
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-04-01
     * @return [type] [description]
     */
    public function examination()
    {
        return $this->hasOne(Examination::class, 'paper_id')->bind(['exam_id' => 'id', 'price', 'user_price', 'credit_redeem', 'credit_redeem_percent', 'module_id']);
    }

    /**
     * 练习人数
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-05-08
     * @return [type] [description]
     */
    public function practiceNum()
    {
        return $this->hasMany(PaperAnswer::class, 'paper_id');
    }
}